<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class RolePermissionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // 创建权限
        $permissions = [
            'view-users',
            'create-users',
            'edit-users',
            'delete-users',
            'view-roles',
            'create-roles',
            'edit-roles',
            'delete-roles',
            'view-permissions',
            'create-permissions',
            'edit-permissions',
            'delete-permissions',
            'assign-permissions',
            'view-dashboard',
            // 组织管理权限
            'view-organizations',
            'create-organizations',
            'edit-organizations',
            'delete-organizations',
            'manage-organization-users',
            // 系统设置权限
            'view-system-settings',
            'create-system-settings',
            'edit-system-settings',
            'delete-system-settings',
            'manage-system-settings',
        ];

        foreach ($permissions as $permission) {
            Permission::firstOrCreate(['name' => $permission]);
        }

        // 创建角色
        $adminRole = Role::firstOrCreate(['name' => 'admin']);
        $editorRole = Role::firstOrCreate(['name' => 'editor']);
        $userRole = Role::firstOrCreate(['name' => 'user']);

        // 给管理员角色分配所有权限
        $adminRole->givePermissionTo(Permission::all());

        // 给编辑者角色分配部分权限
        $editorRole->givePermissionTo([
            'view-users',
            'edit-users',
            'view-dashboard',
        ]);

        // 给普通用户角色分配基本权限
        $userRole->givePermissionTo([
            'view-dashboard',
        ]);

        // 创建管理员用户
        $admin = User::firstOrCreate(
            ['email' => 'admin@example.com'],
            [
                'name' => 'Admin',
                'password' => Hash::make('password'),
            ]
        );
        if (!$admin->hasRole('admin')) {
            $admin->assignRole('admin');
        }

        // 创建编辑者用户
        $editor = User::firstOrCreate(
            ['email' => 'editor@example.com'],
            [
                'name' => 'Editor',
                'password' => Hash::make('password'),
            ]
        );
        if (!$editor->hasRole('editor')) {
            $editor->assignRole('editor');
        }

        // 创建普通用户
        $user = User::firstOrCreate(
            ['email' => 'user@example.com'],
            [
                'name' => 'User',
                'password' => Hash::make('password'),
            ]
        );
        if (!$user->hasRole('user')) {
            $user->assignRole('user');
        }
    }
}
